package com.z.platform.controller;

import com.alibaba.fastjson.JSONObject;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.net.URLDecoder;

public abstract class AbstractController implements Controller {
    @Override
    public void execute(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        MyControllerResult service = this.service(req, resp);
        this.handlerResult(req, resp, service);
    }

    protected abstract MyControllerResult service(HttpServletRequest req, HttpServletResponse resp);

    private void handlerResult(HttpServletRequest req, HttpServletResponse resp, MyControllerResult service) throws IOException {
        Writer writer = null;
        String jsonString = null;
        //判断是否为ajax请求，默认不是
        boolean isAjaxRequest = false;
        if (req.getHeader("x-requested-with") != null && req.getHeader("x-requested-with").equals("XMLHttpRequest")) {
            isAjaxRequest = true;
            jsonString = JSONObject.toJSONString(service);
            String decode = URLDecoder.decode(jsonString, "UTF-8");
            writer = resp.getWriter();
            resp.getWriter().append(decode);
        } else {
            if (isAjaxRequest) {
                resp.setHeader("noAuthentication", "true");
                MyControllerResult resultWithObject = new MyControllerResult(MyControllerResult.Constant.FAIL, "你发的确实是ajax请求，可能因为某些业务问题就走到这里来了","快去看看");
                RequestDispatcher requestDispatcher =req.getRequestDispatcher("http://localhost:26628/");
                writer.write(resultWithObject.convert2Json());
            }else {
                resp.sendRedirect("http://www.baidu.com");
            }
        }
        String accept = req.getHeader("Accept");
        resp.setContentType("text/json;charset=UTF-8");
        writer.close();
        resp.flushBuffer();
    }
}
